import commonUtil from "@utility/commonUtil.js";
import {onActivated, onDeactivated, onMounted} from "vue";

/**
 * @method useLifecycle 组件生命周期
 * @param option {Hooks.LifecycleOption} 生命周期配置
 * @property init {Function} 初始化函数，组件初始化时调用
 * @property load {Function} 加载函数，组件初始化和激活时调用
 * @property unLoad {Function} 卸载函数，组件卸载时调用
 * */
const useLifecycle = (option:Hooks.LifecycleOption):void =>{
    onMounted(() => {
        if(commonUtil.isFun(option.init)) option.init?.();
    })
    onActivated(()=>{
        if(commonUtil.isFun(option.load)) option.load?.();
    });
    onDeactivated(()=>{
        if(commonUtil.isFun(option.unLoad)) option.unLoad?.();
    });
};

/**
 * @method useDebounce 防抖hook，多次频繁操作以最后一次为准
 * @param fn {ArgsFunction} 函数
 * @param delay {Number} 延时时间
 * @returns {ArgsFunction}
 * */
const useDebounce = (fn: ArgsFunction, delay: number = 300):ArgsFunction => {
    let timer: Timeout;
    return (...args: Array<any>): void => {
        clearTimeout(timer)
        timer = setTimeout((): void => {
            fn.call(this, ...args)
        }, delay);
    }
};


/**
 * @method useThrottle 节流hook，多次频繁操作只会执行一次
 * @param fn {ArgsFunction} 函数
 * @param delay {Number} 延时时间
 * @returns {ArgsFunction}
 * */
const useThrottle = (fn: ArgsFunction, delay: number = 300):ArgsFunction => {
    let timer: Timeout | null;
    return (...args: Array<any>): void => {
        if (!timer) {
            timer = setTimeout((): void => {
                fn.apply(this, args);
                clearTimeout(timer as Timeout)
                timer = null;
            }, delay);
        }
    };
};

/**
 * @method useEnv 获取env变量
 * @returns {Hooks.Env} 转换后的值
 * */
const useEnv = (): Hooks.Env => {
    const env: ImportMetaEnv = import.meta.env;
    return {
        nodeEnv: env.VITE_USER_NODE_ENV,
        baseUrl: env.VITE_BASE_URL,
        fileUrl: env.VITE_FILE_URL,
        dateFormat: env.VITE_DATE_FORMAT
    }
};

export {
    useDebounce,
    useThrottle,
    useEnv,
    useLifecycle
}